
/*******************************************************************************
 * The code below this comment is integral part of the project "Jelliphy".
 * 
 * "Jelliphy" is a project created by: 
 * Dispage - Patrizio Gelosi
 * Via A. De Gasperi 91 
 * P. Potenza Picena (MC) - Italy
 * 
 * (Hereby referred to as "DISPAGE")
 * 
 * Copyright (c) 2011 DISPAGE.
 * 
 * @Released on: 02-06-2011
 * @Version: 1.0.00
 * @Build: 1109
 * @Site: http://www.dispage.com
 * @Contacts: http://www.dispage.com/contacts
 * 
 * The contents of this file are released under the GNU General Public License
 * version 3 as published by the Free Software Foundation that can be found at
 * the address "http://opensource.org/licenses/gpl-3.0.html". If the license
 * cannot be found, write to the Free Software Foundation, Inc., 51 Franklin
 * Street, Fifth Floor, Boston, MA 02110-1301 USA.
 * 
 * You may not use the present file except in compliance with the License.
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License
 * for the specific language governing rights and limitations under the
 * License.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * Dispage" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by Dispage".
 * 
 ******************************************************************************/

var MGD = new function () {
	
	var that = this,
		
		currentM9T = '0',
		editingStep = null,
		editingStepValue = null,
		m9tRemap = {
			'old' : {},
			'cur' : {}
		},


		getNextM9T = function (forceM9t) {

			currentM9T = forceM9t ? forceM9t : MGUtils.getUM9t();
			return currentM9T;
		},

		deleteTrasfAhead = function () {

			var inactiveEl = JlQ('.mg-transform-step-inactive');

			if (inactiveEl) {
				that.transforms.splice(that.transforms.length -inactiveEl.length, inactiveEl.length);
				inactiveEl.remove();
			}
		},

		updateTrChain = function (action, actionType, targetText) {

			var nextId, 
				typeName = MGLang.transformChain.typeMap[actionType];

			action = action.replace(/^get\(0\)\./, '');

			JlQ('.mg-panel-transform-chain').css({width: 'auto', left: 'auto'});

			nextId = JlQ('.mg-transform-table tr').length -1;
			JlQ('.mg-transform-table').append('<tr><td><div class="mg-transform-table-id">'+nextId+'</div></td><td><b>'+typeName+'</b></td><td>'+MGUtils.cutText(targetText, 100)+'</td><td>'+JlQ('<div/>').text(MGUtils.cutText(action, 50)).html()+'</td></tr>');

			JlQ('.mg-panel-transform-chain').css('width', JlQ('.mg-panel-transform-chain').width() + 'px');

			JlQ('.mg-transform-table th:last-child, .mg-transform-table td:last-child').css('border-right-width', '0px');

			JlQ('#mg-menu-undo, #mg-menu-reset').removeClass('mg-item-disabled');
		},

		_changeStep = function (value) {

			if (!value) {
				value = editingStepValue;
			}
			deleteTrasfAhead();
			that.undoTransform(that.currentUndoIndex -1);
			that.transforms[editingStep].code = value;
			that.undoTransform(that.currentUndoIndex +1);
			MGED.closeEditarea();
		},

		editTransform = function () {

			editingStep = parseInt(JlQ(this).parent().text()) -1;

			MGED.openEditarea('transform', that.transforms[editingStep].code, {
				syntax: 'js',
				save_callback: 'MGD.changeStep'
			});
		},
	
		elValid = function ($el) {

			if ($el && $el.context && $el.context.tagName && $el.context.tagName.search(/^(?:body|head|html)$/i) == -1 && $el.outerHTML().search(/powered-by-dispage|poweredby_sugarcrm|class=([\'\"])copyrRightLink\1|\xA9/) != -1) {
				MGDial.warning(MGLang.warnings.change_copyright_denied);
				return false;
			}
			else {
				return true;
			}
		},
	
		getJQuerySelector = function (code, notStrict) {

			if (notStrict) {
	 			return code.replace(/^[\s\S]*(\s*JlQ\s*\(\s*([\'\"])[\s\S]*?\2\s*\))[\s\S]*$/i, '$1');
			}
			else {
	 			return code.replace(/^(\s*JlQ\s*\(\s*([\'\"])[\s\S]*?\2\s*\))\.[\s\S]*$/i, '$1');
			}
		},

		getSelFromJQuery = function (code) {

			var m = code.match(/JlQ\s*\(\s*([\'\"])([\s\S]*?)\1\s*\)/);

			return m ? m[2] : '';
		},

		getJQueryAction = function (code) {

			return code.replace(/^\s*JlQ\s*\(\s*([\'\"])[\s\S]*?\1\s*\)\.([\s\S]*)$/i, '$2');
		},

		getJQueryComponents = function (code) {

			return code.match(/^\s*(JlQ\s*\(\s*([\'\"])[\s\S]*?\2\s*\))\.([\s\S]*)$/i);
		},

		getJQueryRule = function (code) {

			var m = code.match(/JlQ\s*\.rule\.filterSheets\("[^"]*"\)/i);

			return m ? m[0] : '';
		},

		getRuleAction = function (code) {

			var m;

			if (code.search(/appendTo/) != -1) {
				m = code.match(/JlQ.rule\(('(?:\\'|[^'])*?')\)\.appendTo/);
				return 'append(' + (m ? m[1] : '') + ')';
			}
			else {
				return 'remove()';
			}
		},

		setOptionals = function ($el, action, optionals, forceParent) {
			
			var $prev = $el.prev();

			if ($prev.length && !forceParent) {
				that.lcGueSel.populateSelectorList($prev, {exclude: ['siblings']});
				optionals.bigBro = that.lcGueSel.selectors[0][0];
			}
			else {
				that.lcGueSel.populateSelectorList($el.parent(), {exclude: ['content']});
				optionals.parent = that.lcGueSel.selectors[0][0];
				if (forceParent && $prev.length) {
					optionals.repIndex = $el.index();
				}
			}
		},

		highlighTrEl = function (ind) {

			if (!ind) return;

			var $el, sel = getJQuerySelector(that.transforms[ind].code);

			eval('$el = ' + sel );
			if (!JlQ('#mg-cursor-trsf').length) {
				JlQ('body').append('<div class="mg-cursors mg-nohighlight" id="mg-cursor-trsf"></div>');
			}
			if ($el.length)	{
				MGP.showElement($el, 'mg-cursor-trsf');
			}
		},

		updateAESelector = function () {

			var oldLeft;

			if (!that.$lastCalled) {
				that.lcGueSel.selectors = [];
				return;
			}
			that.lcGueSel.populateSelectorList(that.$lastCalled);

			oldLeft = JlQ('.mg-panel-advanced-edit').hasClass('mg-hidden') ? 'auto' : JlQ('.mg-panel-advanced-edit').css('left');
			JlQ('.mg-panel-advanced-edit').css({width: 'auto', left: 'auto'});

			if (MGP.currentMode != 'Add') {
				that.lcGueSel.updateElSelector();
			}
			if (!JlQ.browser.opera) {
				JlQ('.mg-panel-advanced-edit').css({width: JlQ('.mg-panel-advanced-edit').width() + 'px',	left: oldLeft});
			}
		};


	that.lastCalled = null;
	that.$lastCalled = null;
	that.lcGueSel = null;
	that.elIsSelected = false;
	that.currentActionType = null;
	that.currentUndoIndex = null;
	that.eaopen = null;
	that.defDisplay = null;
	that.defDispChanged = {};
	that.transforms = [];
	that.loadingTrsf = false;

	that.undoAddMap = {
		before : 'prev()',
		append : 'children().last()',
		after : 'next()',
		replaceWith : 'add()'
	};

	

	that.hasImportant = function ($el) {
		
		return $el.attr('style') && $el.attr('style').search(/!\s*important/i) != -1;
	};

	that.getCurrentM9T = function () {

		return currentM9T;
	};

	that.setCurrentM9T = function (m) {

		currentM9T = m;
	};

	that.addM9T = function ($el) {

		if (!$el.attr('m9t')) {
			$el.attr('m9t', getNextM9T());
		}
	};

	that.restoreOriginal = function () {

		that.newTransform();
		if (MGF.resetLoadedFile) MGF.resetLoadedFile();
		MGTut.nextStep('restore');
	};

	that.newTransform = function () {

		if (that.undoTransform(0)) {
			MGDial.warning(MGLang.warnings.open_no_undo);
			return -1;
		}
		that.m9tRemap = {'old' : {},	'cur' : {}};
		deleteTrasfAhead();
		currentM9T = '0';

		JlQ('.mg-menu-item-edit > li').addClass('mg-item-disabled');
	};

	that.chargeTransform = function (el) {

		var elems = MGUtils.XML2Obj(el),
			comp;

		if (!elems || !elems.code) return;
	
		that.currentActionType = elems.type;

		if (comp = getJQueryComponents(elems.code))	{
			if (elems.type == 'm9tize-elem') {
				MGMV.pasteElementSel = getSelFromJQuery(comp[1]);
			}
			else if (elems.type == 'cut-elem') {
				MGMV.pasteElementSel = getSelFromJQuery(comp[3]);
			}
			that.updateLastCalled(comp[1]);
			that.addTransform(comp[3], '', elems.code, elems.tgtxt, comp[1], elems.m9t);
		}
		else {
			MGCR.assignRuleParams(elems.code, elems.m9t);
			if (!MGCR.selectedRuleInd) {
				MGDial.warning(MGLang.warnings.rule_load_error);
			}
			else {
				//that.transforms.push(elems);
				that.addTransform(getRuleAction(elems.code), '', elems.code, elems.tgtxt);
				MGCR.updateCSS();
				//updateTrChain(getJQueryAction(elems.code), elems.type, elems.tgtxt);
			}
		}
	};

	that.addTransform = function (action, forceActionType, code, targetText, sel, forceM9t) {

		var elBackup, curM9t,
			hasNewM9T = false,
			isARule = false,
			optionals = {},
			isReplace = action.search(/^replace/) != -1,
			$tgElem, m;

		if (MGP.clickingCursor) return;

		if (forceActionType) {
			that.currentActionType = forceActionType;
		}
		if (that.currentActionType == 'cut-elem') {
			JlQ('.mg-target-element').removeClass('mg-target-element');
		}
		if (MGP.currentMode == 'Add' && that.currentActionType != 'add-elem') {
			that.lcGueSel.updateElSelector([['', 'New']]);
		}
		if (that.currentActionType.search(/-rule$/) != -1) {
			$tgElem = MGCR.selectedRule;
			isARule = true;
		}
		else if (that.currentActionType.search(/^(?:cut|copy|m9tize)-elem$/) != -1 && !isReplace && MGMV.pasteElementSel) {
			$tgElem = JlQ(MGMV.pasteElementSel + ':not(.mg-cursor-clone)');
		}
		else {
			$tgElem = that.$lastCalled;
			if (!elValid($tgElem)) {
				if (that.currentActionType == 'resize-elem') {
					MGMV.restoreElemDims($tgElem);
				}
				return;
			}
		}
		if (!targetText) {
			targetText = JlQ('#mg-element-selector > option:eq('+JlQ('#mg-element-selector').attr('selectedIndex')+')').text();
		}
		if (!code) {
			code = "JlQ('" + MGUtils.text2SQString(JlQ('#mg-element-selector').val()) + "')." +action +';';
		}
		if (isARule) {

			curM9t = MGCR.selectedRuleInd;
			if (that.currentActionType == 'add-rule') {
				elBackup = ' ';
			}
			else {
				elBackup = MGCR.selectedRule[0].cssText;
			}
			eval(code);
		}
		else {

			if (!$tgElem) return;

			curM9t = (that.currentActionType == 'change-elem') ? (forceM9t ? forceM9t : currentM9T) : $tgElem.attr('m9t');

			if (targetText != 'New' && $tgElem.parent().length) {
				if (!$tgElem.attr('m9t') && that.currentActionType != 'change-elem') {
					if (!(that.currentActionType == 'cut-elem' && isReplace)) {
						$tgElem.attr('m9t', getNextM9T(forceM9t));
						hasNewM9T = true;
					}

					m = getJQueryComponents(code);
					if (m[1] && that.currentActionType.search(/(?:m9tize|cut)-elem/) == -1) {
						optionals.m9tTrsf = m[1]+".attr('m9t', '"+currentM9T+"');";
					}

					curM9t = currentM9T;
				} 
				else {
					targetText = targetText.replace(/^(m9t=)\w+$/, '$1'+curM9t);
				}
			}
/*
			if (that.currentActionType == 'copy-elem' && code.search(/^\s*jQuery\s*\(\s*[\'\"]\[m9t=/) == -1) {
				optionals.m9tTrsf = getJQuerySelector(code) + ".attr('m9t', '" + MGUtils.add1Digit(currentM9T) + "');";
			}
*/
			if (that.currentActionType == 'resize-elem' && !that.loadingTrsf) {
				elBackup = MGMV.resizeClone.attr('m9t', curM9t);
			}
			else {
				elBackup = $tgElem.clone(true);
			}
			
			if (that.currentActionType == 'cut-elem' || action.match(/^remove\s*\(\s*\)/)) {
				if (isReplace) {
					setOptionals(JlQ(MGMV.pasteElementSel + ':not(.mg-cursor-clone)'), action, optionals, true);
				}
				else {
					setOptionals($tgElem, action, optionals);
				}
			}
			else if (that.currentActionType.search(/^bring-/) != -1) {
				$tgElem.parentsUntil('body').each(function () {
					var $this = JlQ(this);
					$this.data('oldz', $this.css('z-index'));
				});
			}
			$tgElem = that.$lastCalled;

			if (that.currentActionType != 'm9tize-elem' || that.loadingTrsf) {
				eval('$tgElem.' + action);
			}
		}
		deleteTrasfAhead();
		updateTrChain(action, that.currentActionType, targetText);

		if (that.currentActionType == 'copy-elem') {
			m = code.match(/[\s\S]*\.clone\(\).attr\s*\(\s*[\'\"]m9t[\'\"]\s*,\s*[\'\"](\w+)/);
			if (m) {
				hasNewM9T = true;
				curM9t = currentM9T = m[1];
			}
		}
		that.transforms.push(
			JlQ.extend({
				type: that.currentActionType, 
				code: code, 
				backup: elBackup,
				tgtxt: targetText,
				m9t: curM9t, 
				newM9t: hasNewM9T
			}, 
			optionals)
		);
		if (that.currentActionType == 'cut-elem' && isReplace) {
			that.updateLastCalled(JlQ('[m9t=' + curM9t + ']'));
		}
		if (!isARule && MGP.currentMode != 'Add') {
			updateAESelector();
			setTimeout('MGTD.renderDOM(MGD.$lastCalled)', 0);
		}
		that.currentUndoIndex++;
		that.currentActionType = null;
	};

	that.postLoadFile = function () {

		m9tRemap.old = JlQ.extend(m9tRemap.old, m9tRemap.cur);
		m9tRemap.cur = {};
		that.currentUndoIndex = that.transforms.length;
		that.loadingTrsf = false;
	};

	that.changeStep = function (id, value) {

		if (JlQ('.mg-transform-chain .mg-transform-step-inactive').length) {
			editingStepValue = value;
			MGDial.confirm(MGLang.confirms.edit_transform, _changeStep);
		}
		else {
			_changeStep(value);
		}
	};

	that.updateLastCalled = function (sel) {

		if (typeof(sel) == 'string') {
			eval('that.$lastCalled = '+sel);
		}
		else {
			that.$lastCalled = sel;
		}
		that.lastCalled = that.$lastCalled.get(0);
	};

	that.undoTransform = function (undoIndex) {

		var i, sel, preSel, isReplacing, rplEl, trsf;
		
		if (typeof(undoIndex.originalEvent) != 'undefined') {
			undoIndex = parseInt(JlQ(this).parent().text());
		}
		if (!JlQ('.mg-panel-editarea').hasClass('mg-hidden') && that.eaopen == 'transform') {
			MGED.closeEditarea();
		}
		if (that.currentUndoIndex == null || isNaN(that.currentUndoIndex) || undoIndex < that.currentUndoIndex) {

			for (i = (that.currentUndoIndex ? (that.currentUndoIndex -1) : (that.transforms.length -1)); i >= undoIndex; i--) {

				trsf = that.transforms[i];

				preSel = getJQuerySelector(trsf.code);
				sel = 'JlQ("[m9t='+trsf.m9t+']")';

				if (!trsf.backup.length && trsf.type.search(/(?:(?:move|cut|copy|add)-elem|-rule)$/) == -1 && trsf.tgtxt != 'New' && JlQ(sel).length) {
					if (this.nodeName) {
						MGDial.warning(MGLang.warnings.open_no_undo_last);
					}
					return -1;
				}
				JlQ('.mg-transform-table tr:eq('+(i +2)+')').addClass('mg-transform-step-inactive');


				if (trsf.type.search(/^(?:move|cut|copy)-elem$/) != -1) {
					if (trsf.code.indexOf(preSel + '.replace') == -1) {
						eval(sel + '.remove()');
					}
					else {
						isReplacing = true;
					}
				}

				if (trsf.type == 'add-elem') {
					if (trsf.tgtxt == 'body') {
						JlQ('body').children('.mg-added-absolute-element').last().remove();
					}
					else {
						eval(sel + '.' + that.undoAddMap[getJQueryAction(trsf.code).replace(/\([\s\S]*$/, '')] + '.remove()');
					}
//					JlQ('[m9t='+ getM9TFromCode(trsf.code) +']').remove();
				}
				else if (trsf.type.search(/-rule$/) != -1) {
					MGCR.restoreRule(trsf.type, trsf.code, trsf.backup, trsf.m9t);
				}
				else if (trsf.bigBro) {
					eval("JlQ('" + MGUtils.text2SQString(trsf.bigBro) + "').after(trsf.backup.clone(true));");
				}
				else if (trsf.parent) {
					if (isReplacing && trsf.type == 'cut-elem') {
						if (trsf.repIndex) {
							eval("JlQ('" + MGUtils.text2SQString(trsf.parent) + "').children(':eq(" + trsf.repIndex + ")').before(" + sel + ".clone(true).attr('mg-temp-presel', '1'));");
						}
						else {
							eval("JlQ('" + MGUtils.text2SQString(trsf.parent) + "').prepend(" + sel + ".clone(true).attr('mg-temp-presel', '1'));");
						}
						JlQ("[m9t="+trsf.m9t+"]:not([mg-temp-presel])").replaceWith(trsf.backup.clone(true));
						JlQ("[m9t="+trsf.m9t+"][mg-temp-presel]").removeAttr('mg-temp-presel');
					}
					else {
						eval("JlQ('" + MGUtils.text2SQString(trsf.parent) + "').prepend(trsf.backup.clone(true));");
					}
				}
				else {
					if (trsf.tgtxt == 'New') {
						if (typeof(trsf.oldDisplay) != 'undefined') {
							JlQ.extend(that.defDisplay, trsf.oldDisplay);
						}
						else {
							that.$lastCalled = trsf.backup.clone();
						}
						MGP.updateElData(true);
					}
					else {
						eval(sel + '.replaceWith(trsf.backup.clone(true));');
						if (trsf.type != 'change-elem' && !isReplacing) {
							eval('trsf.backup = '+sel+'.clone(true);');
						}
					}
				}
				if (trsf.newM9t) {
					eval(sel + ".removeAttr('m9t')");
					//trsf.backup.removeAttr('m9t');
				}
				if (trsf.type.search(/-rule$/) != -1) {
					MGCR.updateCSS();
				}
				else if (trsf.type.search(/^bring-/) != -1) {
					rplEl = eval(sel);
					rplEl.parentsUntil('body').each(function () {
						var $this = JlQ(this);
						$this.css('z-index', $this.data('oldz'));
					});
				}
			}
		}
		else {

			for (i = that.currentUndoIndex; i < undoIndex; i++) {

				trsf = that.transforms[i];

				JlQ('.mg-transform-table tr:eq('+(i +2)+')').removeClass('mg-transform-step-inactive');
				
				if (trsf.type.search(/-rule$/) != -1) {
					eval(trsf.code);
					MGCR.updateCSS();
				}
				else {

					var cmp = getJQueryComponents(trsf.code),
						el2Add, act;

					if (trsf.tgtxt == 'New') {
						if (typeof(trsf.newDisplay) != 'undefined') {
							JlQ.extend(that.defDisplay, trsf.newDisplay);
						}
						else {
							if (cmp[1] == "JlQ('')") {
								el2Add = 'that.$lastCalled';
								eval(el2Add + '.' + getJQueryAction(trsf.code));
							}
							else {
								eval(trsf.code);
							}
						}
						if (el2Add) {
							MGP.updateElData(true);
						}
						else {
							MGP.characterizeElement(that.$lastCalled);
						}
					}
					else {
						if (trsf.newM9t) {
							
							if (trsf.type == 'cut-elem') {
								trsf.backup.attr("m9t", trsf.m9t);
							}
							else if (trsf.type != 'copy-elem') {
								preSel = getJQuerySelector(trsf.code);
								eval(preSel + '.first().attr("m9t", trsf.m9t)');
							}
						}	
						eval(cmp[1] + '.first().' + cmp[3]);

						if (trsf.backup.is('table') && trsf.type == 'change-attr' && cmp[3].search(/setAttribute\s*\(\s*([\'\"])(?:columns|rows|withheader)\1/) != -1) {
							MGMV.makeDroppable(eval(cmp[1]), true);
						}
						if (trsf.type == 'copy-elem') {
							
							act = cmp[3].replace(/^(\w+)[\s\S]*$/, '$1');

							if (act != 'before') {
								cmp[1] += '.' + that.undoAddMap[act];
							}
							eval(cmp[1] + '.first().attr("m9t", "'+trsf.m9t+'")');
						}
					}
				}
			}
		}
		JlQ('#mg-undo-transform').addClass('mg-invisible');

		that.currentUndoIndex = undoIndex;

		JlQ('#mg-menu-undo').toggleClass('mg-item-disabled', !(that.currentUndoIndex > 0));

		JlQ('#mg-menu-redo').toggleClass('mg-item-disabled', !(that.currentUndoIndex < that.transforms.length));

		if (that.elIsSelected) {
			MGP.toggleElementSelection();
		}
		if (MGMV.pasteElementSel) {
			MGMV.clearSelection();
		}		
		return 0;
	};

	that.highlightTransform = function (ev) {

		var ind, ind2exec, $this = JlQ(this),
			hideUndo = '', hideEdit = '';
		
		if (ev.type == 'mouseover')	{
	
			$this.addClass('mg-transform-highlighted');

			ind = $this.index() -1;
			ind2exec = ind -1;

			if (!ind || ind != that.currentUndoIndex || $this.hasClass('mg-transform-step-inactive') || that.transforms[ind2exec] && that.transforms[ind2exec].tgtxt == 'New')	{
				hideEdit = ' mg-invisible';
			}
			if (!$this.hasClass('mg-transform-step-inactive') && (!that.transforms[ind] || !that.transforms[ind].backup) || ind == that.currentUndoIndex)	{
				hideUndo = ' mg-invisible';
			}
			JlQ('td:first-child > div', this).append('<div id="mg-edit-transform" class="mg-images mg-images-dark mg-images-overlay-left-second JLui-icon-pencil'+hideEdit+'"></div><div id="mg-undo-transform" class="mg-images mg-images-dark mg-images-overlay-left JLui-icon-arrowrefresh-1-s'+hideUndo+'"></div>');
		
			JlQ('#mg-edit-transform').click(editTransform);
			JlQ('#mg-undo-transform').click(that.undoTransform);
			
			if (ind2exec >= 0 && that.transforms[ind2exec] && that.transforms[ind2exec].type.search(/-rule$/) == -1) {
				highlighTrEl(ind2exec);
			}
		}
		else {
			$this.removeClass('mg-transform-highlighted');

			JlQ('td:first-child > div', this).children().remove('div');

			JlQ('#mg-cursor-trsf').remove();
		}
	};

	that.updateDefTransform = function (elId, newV) {

		var newDisplay = {}, oldDisplay = {};

		oldDisplay[elId] = that.defDisplay[elId];
		newDisplay[elId] = newV;

		updateTrChain("css('display', '"+newV+"');", 'change-prop', 'New');

		that.$lastCalled.attr('m9t', getNextM9T());

		that.transforms.push({
			type: 'change-prop',
			code: "''",
			m9t: currentM9T,
			backup: that.$lastCalled.clone(),
			oldDisplay : oldDisplay,
			newDisplay : newDisplay,
			tgtxt: 'New'
		});
		that.currentUndoIndex++;
	};

	that.trsfUndo = function () {

		if (that.currentUndoIndex == null && that.transforms.length || that.currentUndoIndex > 0) {
			if (that.undoTransform(that.currentUndoIndex -1)) {
				MGDial.warning(MGLang.warnings.open_no_undo_last);
			}
		}
	};

	that.trsfRedo = function () {

		if (that.currentUndoIndex < that.transforms.length) {
			that.undoTransform(that.currentUndoIndex +1);
		}
	};

	that.trsfRemoveNew = function () {

		that.transforms = JlQ.grep(that.transforms, function (v, i) {
			var $trEl;
			if (v.tgtxt == 'New') {
				$trEl = JlQ('.mg-transform-table tr:eq('+(i +2)+')');
				if (!$trEl.hasClass('mg-transform-step-inactive')) {
					that.currentUndoIndex--;
				}
				$trEl.addClass('mg-marked2delete');
				return false;
			}
			return true;
		});
		if (JlQ('.mg-marked2delete').length) {
			JlQ('.mg-marked2delete').remove();

			JlQ('.mg-transform-table tr:gt(0)').each(function (i, el) {
				JlQ('.mg-transform-table-id', el).text(i);
			});
		}
	};

	that.selectElement = function (el) {

		that.elIsSelected = false;
		MGP.highlightElement(el);
		MGP.toggleElementSelection();
	};

	that.populateDefDisplay = function () {

		that.defDisplay = {};

		JlQ('.mg-newel-cont').each(function () {
			that.defDisplay[this.id] = JlQ(this).css('display');
		});
		JlQ('.mg-newel-cont').children().addClass('mg-hidden');
	};

	that.syncDefDisplay = function () {

		var bId = MGP.currentAddB.attr('id');
		
		if (that.defDispChanged[bId]) {
			that.$lastCalled.css('display', that.defDisplay[bId]);
		}
	}

	that.init = function () {
		
		that.lcGueSel = new MGGueSel;

		(function(JlQ) {
			JlQ.extend(JlQ.fn, {

				mgAddM9T : function(s) {

					return this.each( function () {

						that.addM9T(JlQ(this));
					});
				}

			});
		})(JlQ);
	};

	that.updateAESelector = updateAESelector;
	that.deleteTrasfAhead = deleteTrasfAhead;
	that.getNextM9T = getNextM9T;
	that.getJQueryRule = getJQueryRule;
};